#region Copyright (c) 2006-2010 Widgetsphere LLC, All Rights Reserved
//--------------------------------------------------------------------- *
//                          Widgetsphere  LLC                           *
//             Copyright (c) 2006-2010 All Rights reserved              *
//                                                                      *
//                                                                      *
//This file and its contents are protected by United States and         *
//International copyright laws.  Unauthorized reproduction and/or       *
//distribution of all or any portion of the code contained herein       *
//is strictly prohibited and will result in severe civil and criminal   *
//penalties.  Any violations of this copyright will be prosecuted       *
//to the fullest extent possible under law.                             *
//                                                                      *
//THE SOURCE CODE CONTAINED HEREIN AND IN RELATED FILES IS PROVIDED     *
//TO THE REGISTERED DEVELOPER FOR THE PURPOSES OF EDUCATION AND         *
//TROUBLESHOOTING. UNDER NO CIRCUMSTANCES MAY ANY PORTION OF THE SOURCE *
//CODE BE DISTRIBUTED, DISCLOSED OR OTHERWISE MADE AVAILABLE TO ANY     *
//THIRD PARTY WITHOUT THE EXPRESS WRITTEN CONSENT OF WIDGETSPHERE LLC   *
//                                                                      *
//UNDER NO CIRCUMSTANCES MAY THE SOURCE CODE BE USED IN WHOLE OR IN     *
//PART, AS THE BASIS FOR CREATING A PRODUCT THAT PROVIDES THE SAME, OR  *
//SUBSTANTIALLY THE SAME, FUNCTIONALITY AS ANY WIDGETSPHERE PRODUCT.    *
//                                                                      *
//THE REGISTERED DEVELOPER ACKNOWLEDGES THAT THIS SOURCE CODE           *
//CONTAINS VALUABLE AND PROPRIETARY TRADE SECRETS OF WIDGETSPHERE,      *
//INC.  THE REGISTERED DEVELOPER AGREES TO EXPEND EVERY EFFORT TO       *
//INSURE ITS CONFIDENTIALITY.                                           *
//                                                                      *
//THE END USER LICENSE AGREEMENT (EULA) ACCOMPANYING THE PRODUCT        *
//PERMITS THE REGISTERED DEVELOPER TO REDISTRIBUTE THE PRODUCT IN       *
//EXECUTABLE FORM ONLY IN SUPPORT OF APPLICATIONS WRITTEN USING         *
//THE PRODUCT.  IT DOES NOT PROVIDE ANY RIGHTS REGARDING THE            *
//SOURCE CODE CONTAINED HEREIN.                                         *
//                                                                      *
//THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE.              *
//--------------------------------------------------------------------- *
#endregion
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Widgetsphere.Generator.Models;
using Widgetsphere.Generator.IOCExtensions.ProjectItemGenerators;
using Widgetsphere.Generator.Common.Util;
using Widgetsphere.Generator.ProjectItemGenerators;

namespace Widgetsphere.Generator.IOCExtensions.ProjectItemGenerators.ObjectExtension
{
	class ObjectExtensionTemplate : BaseIOCExtensionsTemplate
	{
		private StringBuilder sb = new StringBuilder();
		private Table _currentTable = null;

		#region Constructors
		public ObjectExtensionTemplate(ModelRoot model, Table table)
		{
			_model = model;
			_currentTable = table;
		}
		#endregion

		#region BaseClassTemplate overrides
		public override string FileContent
		{
			get
			{
				GenerateContent();
				return sb.ToString();
			}
		}

		public override string FileName
		{
			get { return _currentTable.PascalName + "Extension.Generated.cs"; }
		}

		public string ParentItemName
		{
			get { return _currentTable.PascalName + "Extension.cs"; }
		}

		#endregion

		#region GenerateContent

		private void GenerateContent()
		{
			try
			{
				ValidationHelper.AppendCopyrightInCode(sb, _model);
				this.AppendUsingStatements();
				sb.AppendLine("namespace " + DefaultNamespace);
				sb.AppendLine("{");
				this.AppendClass();
				sb.AppendLine("}");
			}
			catch (Exception ex)
			{
				throw;
			}
		}

		#endregion

		#region namespace / objects

		public void AppendUsingStatements()
		{
			sb.AppendLine("using System;");
			sb.AppendLine("using System.Collections.Generic;");
			sb.AppendLine("using System.Linq;");
			sb.AppendLine("using System.Text;");
			sb.AppendLine("using " + _model.CompanyName + "." + _model.ProjectName + ".DataTransfer;");
			sb.AppendLine("using System.Linq.Expressions;");
			sb.AppendLine("using " + _model.CompanyName + "." + _model.ProjectName + ".Service.Interfaces;");
			sb.AppendLine();
		}

		public void AppendClass()
		{
			sb.AppendLine("	/// <summary>");
			sb.AppendLine("	/// This is an extension class for " + _currentTable.PascalName + " DTO objects and lists");
			sb.AppendLine("	/// </summary>");
			sb.AppendLine("	public static partial class " + _currentTable.PascalName + "Extension");
			sb.AppendLine("	{");
			sb.AppendLine("		#region RunSelect");
			sb.AppendLine("		/// <summary>");
			sb.AppendLine("		/// Select all objects from store.");
			sb.AppendLine("		/// </summary>");
			sb.AppendLine("		public static void RunSelect(this List<" + _currentTable.PascalName + "DTO> list)");
			sb.AppendLine("		{");
			sb.AppendLine("			var proxy = ProxyFactory<" + _currentTable.PascalName + "DTO>.GetProxy();");
			sb.AppendLine("			list.AddRange(proxy.RunSelect());");
			sb.AppendLine("		}");
			sb.AppendLine("		#endregion");
			sb.AppendLine();
			sb.AppendLine("		#region RunSelect Paged");
			sb.AppendLine();
			sb.AppendLine("		/// <summary>");
			sb.AppendLine("		/// Using the specified Where expression, execute a query against the database to return a paged result set.");
			sb.AppendLine("		/// </summary>");
			sb.AppendLine("		public static PagedQueryResults<" + _currentTable.PascalName + "DTO> RunSelect(this List<" + _currentTable.PascalName + "DTO> list, int page, int pageSize, bool ascending, string sortColumn, string linq)");
			sb.AppendLine("		{");
			sb.AppendLine("			var proxy = ProxyFactory<" + _currentTable.PascalName + "DTO>.GetProxy();");
			sb.AppendLine("			PagedQueryResults<" + _currentTable.PascalName + "DTO> retval = proxy.RunSelect(page, pageSize, ascending, sortColumn, linq);");
			sb.AppendLine("			if (retval.GridData != null)");
			sb.AppendLine("				list.AddRange(retval.GridData);");
			sb.AppendLine("			return retval;");
			sb.AppendLine("		}");
			sb.AppendLine();
			sb.AppendLine("		#endregion");
			sb.AppendLine();
			sb.AppendLine("		#region RunSelect Paged");
			sb.AppendLine();
			sb.AppendLine("		/// <summary>");
			sb.AppendLine("		/// Using the specified Where expression, execute a query against the database to return a result set.");
			sb.AppendLine("		/// </summary>");
			sb.AppendLine("		public static void RunSelect(this List<" + _currentTable.PascalName + "DTO> list, string linq)");
			sb.AppendLine("		{");
			sb.AppendLine("			var proxy = ProxyFactory<" + _currentTable.PascalName + "DTO>.GetProxy();");
			sb.AppendLine("			list.AddRange(proxy.RunSelect(linq));");
			sb.AppendLine("		}");
			sb.AppendLine();
			sb.AppendLine("		#endregion");
			sb.AppendLine();
			if (!_currentTable.Immutable)
			{
				sb.AppendLine("		#region Persist");
				sb.AppendLine();
				sb.AppendLine("		/// <summary>");
				sb.AppendLine("		/// Persists this object to store.");
				sb.AppendLine("		/// </summary>");
				sb.AppendLine("		public static void Persist(this " + _currentTable.PascalName + "DTO " + _currentTable.CamelName + ")");
				sb.AppendLine("		{");
				sb.AppendLine("			var proxy = ProxyFactory<" + _currentTable.PascalName + "DTO>.GetProxy();");
				sb.AppendLine("			proxy.Persist(" + _currentTable.CamelName + ");");
				sb.AppendLine("		}");
				sb.AppendLine();
				sb.AppendLine("		/// <summary>");
				sb.AppendLine("		/// Persists this collection to store.");
				sb.AppendLine("		/// </summary>");
				sb.AppendLine("		public static void Persist(this List<" + _currentTable.PascalName + "DTO> " + _currentTable.CamelName + "List)");
				sb.AppendLine("		{");
				sb.AppendLine("			var proxy = ProxyFactory<" + _currentTable.PascalName + "DTO>.GetProxy();");
				sb.AppendLine("			proxy.Persist(" + _currentTable.CamelName + "List);");
				sb.AppendLine("		}");
				sb.AppendLine();
				sb.AppendLine("		#endregion");
				sb.AppendLine();
			}

			sb.AppendLine("		#region " + _currentTable.PascalName + " SelectUsingPK");
			sb.AppendLine();
			sb.AppendLine("		/// <summary>");
			sb.AppendLine("		/// Select a single object from this collection by its primary key.");
			sb.AppendLine("		/// </summary>");
			sb.Append("		public static bool SelectByPrimaryKey(this " + _currentTable.PascalName + "DTO " + _currentTable.CamelName + ", ");

			int ii = 0;
			foreach (Column column in _currentTable.PrimaryKeyColumns.OrderBy(x => x.Name))
			{
				sb.Append(column.GetCodeType() + " " + column.CamelName);
				if (ii < _currentTable.PrimaryKeyColumns.Count - 1)
					sb.Append(", ");
				ii++;
			}
			sb.AppendLine(")");
			sb.AppendLine("		{");
			sb.AppendLine("			var proxy = ProxyFactory<" + _currentTable.PascalName + "DTO>.GetProxy();");
			sb.AppendLine("			I" + _currentTable.PascalName + "Service " + _currentTable.CamelName + "Service = (I" + _currentTable.PascalName + "Service)proxy;");
			sb.Append("			var item = " + _currentTable.CamelName + "Service.SelectByPrimaryKey(");

			ii = 0;
			foreach (Column column in _currentTable.PrimaryKeyColumns.OrderBy(x => x.Name))
			{
				sb.Append(column.CamelName + "");
				if (ii < _currentTable.PrimaryKeyColumns.Count - 1)
					sb.Append(", ");
				ii++;
			}
			sb.AppendLine(");");
			sb.AppendLine("			if (item == null) return false;");
			sb.AppendLine("			CopyObject(item, " + _currentTable.CamelName + ");");
			sb.AppendLine("			return true;");
			sb.AppendLine("		}");
			sb.AppendLine();
			sb.AppendLine("		#endregion");
			sb.AppendLine();

			#region Select by Foreign Key
			sb.AppendLine("		#region " + _currentTable.PascalName + " Select By Foreign Key");

			List<Relation> allRelations = _currentTable.GetRelationsFullHierarchy();
			List<string> methodList = new List<string>();
			foreach (Relation relation in allRelations)
			{
				Table parentTable = (Table)relation.ParentTableRef.Object;
				Table childTable = (Table)relation.ChildTableRef.Object;

				//Handle relations by inheritance
				if (_currentTable.IsInheritedFrom(childTable))
					childTable = _currentTable;

				if (childTable.IsInheritedFrom(parentTable))
				{
					//Do Nothing
				}
				else if (childTable.Generated && parentTable.Generated)
				{
					//If the this is the child of the relation then find the parent ITEM
					if (childTable == _currentTable)
					{
						string methodName = "Get" + relation.PascalRoleName + parentTable.PascalName;
						if (!methodList.Contains(methodName))
						{
							methodList.Add(methodName);

							sb.AppendLine("		/// <summary>");
							sb.AppendLine("		/// Get the related '" + parentTable.PascalName + "' DTO object");
							sb.AppendLine("		/// </summary>");
							sb.AppendLine("		public static " + parentTable.PascalName + "DTO " + methodName + "(this " + childTable.PascalName + "DTO item)");
							sb.AppendLine("		{");
							sb.AppendLine("			var proxy = ProxyFactory<" + childTable.PascalName + "DTO>.GetProxy();");
							sb.AppendLine("			I" + childTable.PascalName + "Service service = (I" + childTable.PascalName + "Service)proxy;");
							sb.AppendLine("			return service.Get" + relation.PascalRoleName + parentTable.PascalName + "Item(item);");
							sb.AppendLine("		}");
							sb.AppendLine();
						}
					}
					//If the this is the parent of the relation then find the child LIST
					else if (parentTable == _currentTable)
					{
						string methodName = "Get" + relation.PascalRoleName + childTable.PascalName + "List";
						if (!methodList.Contains(methodName))
						{
							methodList.Add(methodName);

							sb.AppendLine("		/// <summary>");
							sb.AppendLine("		/// Get the related '" + childTable.PascalName + "' DTO list");
							sb.AppendLine("		/// </summary>");
							sb.AppendLine("		public static " + childTable.PascalName + "DTO[] " + methodName + "(this " + parentTable.PascalName + "DTO item)");
							sb.AppendLine("		{");
							sb.AppendLine("			var proxy = ProxyFactory<" + parentTable.PascalName + "DTO>.GetProxy();");
							sb.AppendLine("			I" + parentTable.PascalName + "Service service = (I" + parentTable.PascalName + "Service)proxy;");
							sb.AppendLine("			return service.Get" + relation.PascalRoleName + childTable.PascalName + "List(item).ToArray();");
							sb.AppendLine("		}");
							sb.AppendLine();
						}
					}
				}

			}

			sb.AppendLine();
			sb.AppendLine("		#endregion");
			sb.AppendLine();
			#endregion

			#region Select By Searchable

			sb.AppendLine("		#region Select by Fields");
			sb.AppendLine();

			foreach (Column column in _currentTable.GetColumnsFullHierarchy().Where(x => x.Generated && x.IsSearchable))
			{
				sb.AppendLine("		/// <summary>");
				sb.AppendLine("		/// Selects list of objects by " + column.PascalName);
				sb.AppendLine("		/// </summary>");
				sb.AppendLine("		public static List<" + _currentTable.PascalName + "DTO> SelectByConstraintName(this " + _currentTable.PascalName + "DTO item, " + column.GetCodeType() + " " + column.CamelName + ")");
				sb.AppendLine("		{");
				sb.AppendLine("			var proxy = ProxyFactory<" + _currentTable.PascalName + "DTO>.GetProxy();");
				sb.AppendLine("			I" + _currentTable.PascalName + "Service service = (I" + _currentTable.PascalName + "Service)proxy;");
				sb.AppendLine("			return service.SelectBy" + column.PascalName + "(item, " + column.CamelName + ");");
				sb.AppendLine("		}");
				sb.AppendLine();
			}

			sb.AppendLine("		#endregion");

			#endregion

			#region Delete
			if (!_currentTable.Immutable)
			{
				sb.AppendLine("		#region Delete");
				sb.AppendLine();
				sb.AppendLine("		/// <summary>");
				sb.AppendLine("		/// Delete a single object.");
				sb.AppendLine("		/// </summary>");
				sb.AppendLine("		public static void Delete(this " + _currentTable.PascalName + "DTO " + _currentTable.CamelName + ")");
				sb.AppendLine("		{");
				sb.AppendLine("			var proxy = ProxyFactory<" + _currentTable.PascalName + "DTO>.GetProxy();");
				sb.AppendLine("			I" + _currentTable.PascalName + "Service " + _currentTable.CamelName + "Service = (I" + _currentTable.PascalName + "Service)proxy;");
				sb.AppendLine("			" + _currentTable.CamelName + "Service.Delete(" + _currentTable.CamelName + ");");
				sb.AppendLine("		}");
				sb.AppendLine();
				sb.AppendLine("		#endregion");
				sb.AppendLine();
			}
			#endregion

			sb.AppendLine("		/// <summary>");
			sb.AppendLine("		/// Clones one DTO to another.");
			sb.AppendLine("		/// </summary>");
			sb.AppendLine("		internal static void CopyObject(" + _currentTable.PascalName + "DTO source, " + _currentTable.PascalName + "DTO destination)");
			sb.AppendLine("		{");
			foreach (Column column in _currentTable.GetColumnsFullHierarchy().Where(x => x.Generated))
			{
				sb.AppendLine("			destination." + column.PascalName + " = source." + column.PascalName + ";");
			}			
			sb.AppendLine("		}");
			sb.AppendLine();

			sb.AppendLine("	}");
		}

		#endregion

		#region Methods

		private string PrimaryKeyColumnList(Table table, bool includeType)
		{
			StringBuilder output = new StringBuilder();
			foreach (Column dc in table.PrimaryKeyColumns.OrderBy(x => x.Name))
			{
				if (includeType) output.Append(dc.GetCodeType() + " ");
				output.Append(dc.CamelName);
				output.Append(", ");
			}
			string retval = output.ToString();
			if (retval.EndsWith(", ")) retval = retval.Substring(0, retval.Length - 2);
			return retval;
		}

		#endregion

	}
}